﻿using System.Diagnostics;
using System.Net.Sockets;

namespace BlazorAdmin.Tcp.Server
{
    /// <summary>
    /// Tcp服务连接会话实体
    /// </summary>
    [DebuggerDisplay("[{Key}]{Client}:{LastActivityTime}")]
    public class TcpToken : EventArgs
    {
        /// <summary>
        /// 客户端会话ID
        /// </summary>
        private readonly string key;

        public TcpToken()
        {
            key = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
        }

        /// <summary>
        /// 会话对象的唯一标识实体类
        /// </summary>
        public string Key => key;

        /// <summary>
        /// Tcp服务套接字实体对象
        /// </summary>
        public Socket? Server { get; internal set; }

        private Socket? client = null;

        /// <summary>
        /// 连接到Tcp服务的客户端套接字
        /// </summary>
        public Socket? Client
        {
            get => client;
            internal set
            {
                client = value;
                clientPoint = null != client ? client.RemoteEndPoint?.ToString() : string.Empty;
            }
        }

        private string? clientPoint = string.Empty;

        /// <summary>
        /// 连接到Tcp服务的客户端套接字
        /// </summary>
        public string? ClientPoint => clientPoint;

        /// <summary>
        /// 连接时间
        /// </summary>
        public DateTime ConnectTime { get; internal set; }

        /// <summary>
        /// 最后活动时间
        /// </summary>
        public DateTime LastActivityTime { get; internal set; }

        /// <summary>
        /// 最后操作消息
        /// </summary>
        public string? LastMessage { get; set; }

        /// <summary>
        /// 是否正在关闭
        /// </summary>
        public bool IsClosing { get; internal set; }

        /// <summary>
        /// 重置
        /// </summary>
        public void Reset()
        {
            Client = null;
            LastActivityTime = ConnectTime = DateTime.MinValue;
            LastMessage = string.Empty;
        }
    }
}
